<template>
  <div class="tag-sys-dict-user-data">
    <el-card>
      <tag-content-header add refresh setting @toolFun="toolFun" :settingData="columns">
        <template #title>
          <!-- <icon-svg name="iconRead"></icon-svg> -->
          <span class="title-text">{{ headerTitle ? headerTitle : '用户字典数据-' + dictType }}</span>
        </template>
      </tag-content-header>
      <tag-table
        ref="table"
        @refresh="getList"
        :data="dataList"
        :loading="loading"
        :columns="columns"
        :pagination="false"
        :maxHeight="maxTableHeight"
      >
        <template #operation="{ scope }">
          <div class="operation-button-box">
            <el-tooltip effect="dark" content="切换状态" placement="top" :enterable="false">
              <el-switch
                active-color="#74c4b9"
                v-model="scope.row.dictDataStatus"
                :active-value="0"
                :inactive-value="1"
                @change="toggleStatus(scope)"
              >
              </el-switch>
            </el-tooltip>
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <icon-svg name="iconEdit" class="svg-edit" @click.native="handleEdit('edit', scope.row)"></icon-svg>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <icon-svg name="iconDelete" class="svg-delete" @click.native="handleDelete(scope.row)"></icon-svg>
            </el-tooltip>
          </div>
        </template>
      </tag-table>
    </el-card>

    <el-drawer
      :title="drawerTitle[drawerType]"
      size="60%"
      :visible.sync="drawerVisible"
      direction="rtl"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      :destroy-on-close="true"
      :before-close="clearDialog"
      custom-class="tag-drawer user-drawer tag-dict-user-drawer"
      v-drawerResize
    >
      <div class="drawer-wrap">
        <div class="drawer-content tag-scrollbar">
          <el-form :model="editForm" label-width="150px" :rules="editFormRules" ref="editForm">
            <h4 class="type-title">
              <div class="icon-box"><icon-svg name="iconBase"></icon-svg></div>
              <span>基本信息</span>
            </h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="字典键值" prop="dictKey">
                  <el-input placeholder="请输入字典键值" :readonly="!editable" v-model="editForm.dictKey"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="字典标签" prop="dictTag">
                  <el-input placeholder="请输入字典标签" v-model="editForm.dictTag"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <template v-if="dictId === 13">
                <el-col :span="12">
                  <el-form-item label="数据库类型" prop="db_val">
                    <el-input placeholder="请输入数据库类型" v-model="editForm.db_val"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="数据库默认值" prop="check_type">
                    <el-input placeholder="请输入数据库默认值" v-model="editForm.check_type"></el-input>
                  </el-form-item>
                </el-col>
              </template>
              <el-col :span="24" v-else-if="dictId === 23">
                <el-form-item
                  label="应用渠道英文名称"
                  prop="cmntStr"
                  :rules="[
                    { required: true, message: '应用渠道英文名称不能为空', trigger: 'blur' },
                    {
                      validator: appValidator,
                      trigger: 'blur'
                    }
                  ]"
                >
                  <el-input placeholder="请输入应用渠道英文名称" v-model="editForm.cmntStr"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-else>
                <el-form-item label="备注信息" prop="cmntStr">
                  <el-input
                    type="textarea"
                    placeholder="请输入备注信息，最大不能超过100个字符"
                    v-model="editForm.cmntStr"
                    :rows="3"
                    resize="none"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- dictId=13 取值类型增加挂载编码功能 -->
          <template v-if="dictId === 13 && $auth('pac:pacThirdCode:view') && drawerType === 'edit'">
            <el-form :model="codeForm" label-width="130px" :rules="codeFormRules" ref="codeForm">
              <h4 class="type-title">
                <div class="icon-box"><icon-svg name="iconCode"></icon-svg></div>
                <span>第三方编码</span>
              </h4>
              <div class="code-wrap">
                <span class="code-btn">
                  <span class="edit-btn" @click="codeEditable = true">
                    <el-tooltip effect="dark" content="修改第三方编码" placement="top" :enterable="false">
                      <i class="el-icon-edit"></i>
                    </el-tooltip>
                  </span>
                  <span class="delete-btn" @click="deleteCode">
                    <el-tooltip effect="dark" content="删除第三方编码" placement="top" :enterable="false">
                      <i class="el-icon-close"></i>
                    </el-tooltip>
                  </span>
                </span>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="第三方编码" prop="thirdPartyCode">
                      <template slot="label" v-if="codeEditable">
                        <span
                          >第三方编码<el-popover
                            effect="dark"
                            title="最新编码信息"
                            :content="codeInfo.lastCode || '暂无'"
                            placement="top"
                            trigger="hover"
                            @show="getLastCode"
                          >
                            <i class="el-icon-info" slot="reference"></i>
                          </el-popover>
                        </span>
                      </template>
                      <span v-if="!codeEditable">{{ codeInfo.thirdPartyCode || '暂无' }}</span>
                      <el-input placeholder="请输入第三方编码" v-model="codeForm.thirdPartyCode" v-else></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item label="编码映射描述" prop="codeDesc">
                      <span v-if="!codeEditable">{{ codeInfo.codeDesc || '暂无' }}</span>
                      <el-input
                        placeholder="请输入编码映射描述"
                        v-model="codeForm.codeDesc"
                        type="textarea"
                        :rows="3"
                        resize="none"
                        v-else
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="codeEditable">
                  <el-col align="right">
                    <el-button @click="cancelEditCode">取消</el-button>
                    <el-button type="primary" @click="submitCode">确定</el-button>
                  </el-col>
                </el-row>
              </div>
            </el-form>
          </template>
        </div>
      </div>
      <div class="drawer-btns">
        <el-button @click="clearDialog">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  props: {
    headerTitle: {
      type: String
    }
  },
  data() {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('第三方编码不能为空'))
      } else {
        let isAuth = true
        for (var i = 0; i < value.length; i++) {
          let n = value.charCodeAt(i)
          if (!((n >= 48 && n <= 57) || (n >= 65 && n <= 90) || (n >= 97 && n <= 122) || n === 95)) {
            isAuth = false
          }
        }
        if (!isAuth) {
          return callback(new Error('第三方编码只能输入数字、字母或者下划线'))
        } else {
          return callback()
        }
      }
    }
    return {
      editable: true,
      dataList: [],
      loading: false,
      columns: [
        {
          show: true,
          label: '字典键值',
          prop: 'dictKey',
          align: 'center'
        },
        {
          show: true,
          label: '字典标签',
          prop: 'dictTag',
          align: 'center'
        },
        {
          show: false,
          label: '状态',
          prop: 'dictDataStatus',
          width: '120',
          dict: 'status',
          align: 'center'
        },
        {
          show: 'fixed',
          label: '操作',
          prop: 'operation',
          align: 'center',
          width: 200
        }
      ],
      drawerVisible: false,
      drawerType: 'add',
      drawerTitle: {
        add: '新增',
        edit: '编辑'
      },
      dictId: '',
      dictType: '',
      dictDataId: '',
      editForm: {
        dictKey: '',
        dictDataId: '',
        dictTag: '',
        dictDataStatus: 0,
        cmntStr: '',
        db_val: '',
        check_type: ''
      },
      editFormRules: {
        dictKey: [
          { required: true, message: '字典键值不能为空', trigger: 'blur' },
          { validator: this.$validator(/^[0-9]{1,9}$/, '字典键值只能输入9位以内的数字'), trigger: 'blur' }
        ],
        dictTag: [
          { required: true, message: '字典标签不能为空', trigger: 'blur' },
          { max: 30, message: '字典标签不能超过30个字符', trigger: 'blur' }
        ],
        cmntStr: [{ max: 100, message: '备注信息不能超过100个字符', trigger: 'blur' }],
        db_val: [
          { required: true, message: '数据库类型不能为空', trigger: 'blur' },
          { validator: this.$validator(/^[0-9a-zA-Z]+$/, '数据库类型只能输入英文或数字'), trigger: 'blur' }
        ],
        check_type: [
          { validator: this.$validator(/^[0-9a-zA-Z]+$/, '数据库默认值只能输入英文或数字'), trigger: 'blur' }
        ]
      },
      codeEditable: false,
      codeInfo: {
        thirdPartyCode: '',
        codeDesc: '',
        lastCode: ''
      },
      codeForm: {
        thirdPartyCode: '',
        codeDesc: ''
      },
      codeFormRules: {
        thirdPartyCode: [{ validator: checkCode, trigger: 'blur' }]
      }
    }
  },
  computed: {
    maxTableHeight() {
      // 表格最大高度 =  可视窗口高度 - 顶栏高度50 - 内容容器padding - 页面容器padding和border - 工具栏最小高度 - 描述框高度
      var paddingHeight = 0
      if (this.$route.meta.isTab) {
        paddingHeight = 70
      } else {
        paddingHeight = 30
      }
      var height = this.$store.state.common.documentClientHeight - 50 - paddingHeight - 22 - 40
      return height
    }
  },
  // created() {
  //   this.init()
  // },
  beforeRouteEnter(to, from, next) {
    if (to.params.dictId) {
      next()
    } else {
      next(vm => {
        vm.$router.replace({ name: '404' })
      })
    }
  },
  methods: {
    initData(dictId = '') {
      this.dictId = dictId || this.$route.params.dictId
      this.getList()
    },
    getList() {
      if (!this.dictId) return
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('sys/sysClientDictDataMgr/listByDictId/' + this.dictId),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code == '0') {
          if (data.data.dictId == this.dictId) {
            this.dictType = data.data.dictType
            this.dataList = data.data.sysDictDataDTOS
          }
        } else {
          this.$message.error('获取字典数据列表失败！')
        }
        this.loading = false
      })
    },
    toolFun(operation) {
      switch (operation) {
        case 'add':
          // 新增动作
          this.handleEdit()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    handleEdit(type = 'add', scope = {}) {
      this.drawerType = type
      switch (type) {
        case 'add':
          this.editable = true
          this.drawerVisible = true
          break
        case 'edit':
          this.editable = false
          this.getDetail(scope)
          break
      }
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = {
            dictId: this.dictId,
            dictKey: this.editForm.dictKey,
            dictTag: this.editForm.dictTag,
            cmntStr: this.dictId === 13 ? this.editForm.db_val + '|' + this.editForm.check_type : this.editForm.cmntStr
          }
          if (this.drawerType === 'edit') {
            params = Object.assign({}, params, {
              dictDataId: this.dictDataId,
              dictDataStatus: this.editForm.dictDataStatus
            })
          }
          this.$ajax({
            url: this.$ajax.setUrl('sys/sysClientDictDataMgr'),
            method: this.drawerType === 'add' ? 'post' : 'put',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.drawerVisible = false
              this.clearDialog()
              this.getList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    getDetail(scope) {
      this.$ajax({
        url: this.$ajax.setUrl('sys/sysClientDictDataMgr/' + scope.dictDataId),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dictDataId = data.data.dictDataId || ''
          this.editForm.dictKey = data.data.dictKey
          this.editForm.dictDataId = data.data.dictDataId || ''
          this.editForm.dictTag = data.data.dictTag || ''
          this.editForm.dictDataStatus = data.data.dictDataStatus
          this.editForm.cmntStr = data.data.cmntStr || ''
          if (this.dictId === 13) {
            this.editForm.db_val = data.data.cmntStr.split('|')[0]
            this.editForm.check_type = data.data.cmntStr.split('|')[1]
          }
          this.drawerVisible = true
          if (this.dictId === 13 && this.$auth('pac:pacThirdCode:view') && this.drawerType === 'edit')
            this.getThirdCode()
        } else {
          this.$message('获取字典数据信息失败！')
        }
      })
    },
    getThirdCode() {
      this.$ajax({
        url: this.$ajax.setUrl(`pac/catalog/99/${this.editForm.dictDataId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.codeInfo.thirdPartyCode = data.data ? data.data.thirdPartyCode : ''
          this.codeInfo.codeDesc = data.data ? data.data.codeDesc : ''
          this.codeForm.thirdPartyCode = data.data ? data.data.thirdPartyCode : ''
          this.codeForm.codeDesc = data.data ? data.data.codeDesc : ''
        } else {
          this.$message('获取字典数据信息失败！')
        }
      })
    },
    getLastCode() {
      this.$ajax({
        url: this.$ajax.setUrl('pac/latest/99'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.codeInfo.lastCode = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    submitCode() {
      this.$refs['codeForm'].validate(valid => {
        if (valid) {
          this.$ajax({
            url: this.$ajax.setUrl('pac'),
            method: 'post',
            data: this.$ajax.setData({
              codeType: 99,
              internalCode: this.editForm.dictDataId,
              thirdPartyCode: this.codeForm.thirdPartyCode,
              codeDesc: this.codeForm.codeDesc
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.codeEditable = false
              this.getThirdCode()
              this.$message.success(data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    deleteCode() {
      this.$confirm('确定删除第三方编码？').then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`pac/99/${this.editForm.dictDataId}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.getThirdCode()
            this.$message.success(data.msg)
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    toggleStatus(scope) {
      let params = {
        dictId: this.dictId,
        dictDataId: scope.row.dictDataId,
        dictKey: scope.row.dictKey,
        dictTag: scope.row.dictTag,
        dictDataStatus: scope.row.dictDataStatus,
        cmntStr: scope.row.cmntStr
      }
      this.$ajax({
        url: this.$ajax.setUrl('sys/sysClientDictDataMgr'),
        method: 'put',
        data: this.$ajax.setData(params)
      }).then(({ data }) => {
        let mes = { type: '', message: '' }
        if (data && data.code === '0') {
          mes.type = 'success'
          mes.message = '操作成功'
        } else {
          mes.type = 'error'
          mes.message = data.data
        }
        this.getList()
        this.$message({
          message: mes.message,
          type: mes.type,
          duration: 2000
        })
      })
    },
    handleDelete(scope) {
      if (!scope.dictDataId) return
      this.$confirm('确认删除【' + scope.dictTag + '】？')
        .then(() => {
          let messageBox = document.getElementsByClassName('el-message-box__wrapper')
          messageBox[0].focus() // 防止按空格键重复确定
          this.$ajax({
            url: this.$ajax.setUrl('sys/sysClientDictDataMgr/' + scope.dictDataId),
            method: 'delete',
            params: this.$ajax.setParams()
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.getList()
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.deleteThirdCode(scope)
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        })
        .catch(() => {
          return
        })
    },
    deleteThirdCode(scope) {
      this.$ajax({
        url: this.$ajax.setUrl(`pac/99/${scope.dictDataId}`),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          // 删除第三方编码成功
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    clearDialog() {
      this.dictDataId = ''
      this.editForm.dictKey = ''
      this.editForm.dictDataId = ''
      this.editForm.dictTag = ''
      this.editForm.dictDataStatus = ''
      this.editForm.cmntStr = ''
      this.editForm.db_val = ''
      this.editForm.check_type = ''
      this.codeInfo.thirdPartyCode = ''
      this.codeInfo.codeDesc = ''
      this.codeForm.thirdPartyCode = ''
      this.codeForm.codeDesc = ''
      this.codeInfo.lastCode = ''
      this.codeEditable = false
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
      this.drawerVisible = false
    },
    cancelEditCode() {
      this.codeForm.thirdPartyCode = this.codeInfo.thirdPartyCode
      this.codeForm.codeDesc = this.codeInfo.codeDesc
      this.codeEditable = false
      this.$nextTick(() => this.$refs.codeForm.clearValidate())
    },
    appValidator(rule, value, callback) {
      let patt = /^[a-zA-Z]+$/
      if (!patt.test(value)) {
        return callback(new Error('应用渠道英文名只能输入英文字母'))
      } else {
        return callback()
      }
    }
  }
}
</script>

<style lang="scss">
.tag-dict-user-drawer {
  .code-wrap {
    padding: 20px;
    border: 1px dotted $border-color;
    position: relative;
  }
  .code-btn {
    position: absolute;
    top: 0;
    right: 0;
    width: 50px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    background-color: #7c7c7c;
    border-bottom-left-radius: 6px;
    cursor: pointer;
    .edit-btn {
      width: 20px;
      margin-right: 5px;
      color: #ffc35c;
    }
    .delete-btn {
      width: 20px;
      color: #87cefa;
    }
  }
  .el-icon-info {
    margin-left: 5px;
  }
}
</style>
